package com.gf.snoopy.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;

import com.gf.snoopy.dto.DownloadFile;
import com.gf.snoopy.platform.exception.PokeErrorCode;
import com.gf.snoopy.platform.exception.PokeException;

public class ZipUtil {
	
	private static final Logger logger = Logger.getLogger(ZipUtil.class);

	public static DownloadFile zip(String tempPath,String fileName,List<DownloadFile> files) throws PokeException {
		if (CollectionUtils.isEmpty(files)) {
			return null;
		}
		String address = tempPath+fileName;
		DownloadFile downloadFile = null;
		try {
			File outputFile = new File(address);
			if(outputFile.exists()){
				outputFile.delete();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
			ZipOutputStream zipOut = new ZipOutputStream(fileOutputStream);
			zipOut.setEncoding("UTF-8");
			for(DownloadFile file:files){
				zipFile(file,zipOut);
			}
			zipOut.close();
			fileOutputStream.close();
			
		    InputStream input = new FileInputStream(outputFile);   
		    byte[] byt = new byte[input.available()];  
		    input.read(byt);  
		    input.close();
			downloadFile = new DownloadFile(fileName,byt);	
			outputFile.delete();
			
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			throw new PokeException(PokeErrorCode.INVALID_PARAM, "关闭文件流出错"+e.getMessage());
		}
		return downloadFile;
	}

	public static void zipFile(DownloadFile file, ZipOutputStream ouputStream) throws PokeException {
		ZipEntry entry = new ZipEntry(file.getFileName());
		try {
			ouputStream.putNextEntry(entry);
			ouputStream.write(file.getFileData());
			ouputStream.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			throw new PokeException(PokeErrorCode.INVALID_PARAM, "打包文件("+file.getFileName()+")出错"+e.getMessage());
		}
	}

}
